package com.soup.lab.tools.faker.source;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

public class BigFileSourceReader implements SourceReader<String> {

    private final ReaderSource readerSource;

    private final int batch;

    public BigFileSourceReader(ReaderSource readerSource, int batch) {
        this.readerSource = readerSource;
        this.batch = batch;
    }

    @Override
    public Iterator<String> iterator() {
        try {
            BufferedReader reader = readerSource.getAsReader();
            return new BatchReadIterator(reader, batch);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyIterator();
    }

    private static class BatchReadIterator extends PageableIterator<String> implements AutoCloseable {
        private final BufferedReader reader;

        public BatchReadIterator(BufferedReader reader, int pageSize) {
            super(pageSize);
            this.reader = reader;
            this.cacheMaxIndex = -1;
            this.currentIndex = 0;
        }

        @Override
        protected void readPage() {
            if (exhausted) {
                return;
            }
            String[] newCache = new String[pageSize];
            int count = 0;
            try {
                while (count < pageSize) {
                    String line = reader.readLine();
                    if (line == null) {
                        close();
                        break;
                    }
                    newCache[count++] = line;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                currentIndex = 0;
                cache = newCache;
                cacheMaxIndex = count - 1;
            }
        }

        @Override
        public void close() throws Exception {
            exhausted = true;
            reader.close();
        }
    }

}
